package com.imooc.mall.controller;

import com.imooc.mall.common.ResultInfo;
import com.imooc.mall.common.ResultInfoUtil;
import com.imooc.mall.enums.ResultEnum;
import com.imooc.mall.exception.MallException;
import com.imooc.mall.exception.UserLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionController {

    @ExceptionHandler(Exception.class)
    //自定义返回状态码@ResponseStatus(value = HttpStatus.FORBIDDEN)  403
    public ResultInfo exceptionHandle(Exception e) {
        if (e instanceof MallException) {
            MallException m = (MallException) e;
            return ResultInfoUtil.error(m.getCode(), m.getMessage());
        } else if (e instanceof NullPointerException) {
            NullPointerException n = (NullPointerException) e;
            return ResultInfoUtil.error(ResultEnum.NULL_POINT_EXCEPTION.getCode(),
                    ResultEnum.NULL_POINT_EXCEPTION.getMsg());
        } else if (e instanceof IndexOutOfBoundsException) {
            IndexOutOfBoundsException i = (IndexOutOfBoundsException) e;
            return ResultInfoUtil.error(ResultEnum.INDEX_OUT_BOUNDS_EXCEPTION.getCode(),
                    ResultEnum.INDEX_OUT_BOUNDS_EXCEPTION.getMsg());
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException m = (MethodArgumentNotValidException) e;
            return ResultInfoUtil.error(0, m.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof UserLoginException) {
            UserLoginException l = (UserLoginException) e;
            return ResultInfoUtil.error(ResultEnum.NEED_LOGIN.getCode(),
                    ResultEnum.NEED_LOGIN.getMsg());
        } else {
            log.error("系统异常", e);
            return ResultInfoUtil.error(ResultEnum.UNKNOWN.getCode(),
                    ResultEnum.UNKNOWN.getMsg());
        }
    }
}
